import React from 'react';
import {Col, Row, Modal, Descriptions, Badge, Skeleton} from 'antd';
import styles from './index.less';
import {connect} from "dva";
import {trigger} from "@/utils/utils";
import {dateFormat, convertDateFromString} from "@/utils/time";
import echarts from 'echarts'
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import PredictionDetail from "../PredictionDetail";
import {getLatestTime} from "@/services/indicator";

class Prediction extends React.Component {
  stopLoop = false;
  state = {
    scoreQuntile: null,
    predictionData: {
      predictScore: null,
      curScore: null,
      bestScore: null,
      shoude: null,
      status: {
        "CG_LT_GL_GL04_TQXZS_status": "正常",
        "CG_LT_GL_GL04_LFLL_status": "正常",
        "CG_LT_GL_GL04_FYLL_status": "正常",
        "CG_LT_GL_GL04_FCokeRate_status": "正常",
        "CG_LT_GL_GL04_FCoalRate_status": "正常",
        "CG_LT_GL_GL04_RFWD_status": "正常",
        "CG_LT_GL_GL04_SBYCZB_status": "正常",
        "CG_LT_GL_GL04_XBYCZB_status": "正常",
      },
      statusDict: {
        "CG_LT_GL_GL04_TQXZS_status": "透气性指数",
        // "CG_LT_GL_GL04_FZWD_status": "",
        "CG_LT_GL_GL04_LFLL_status": "冷风流量",
        "CG_LT_GL_GL04_FYLL_status": "富氧流量",
        "CG_LT_GL_GL04_FCokeRate_status": "焦比",
        "CG_LT_GL_GL04_FCoalRate_status": "煤比",
        "CG_LT_GL_GL04_RFWD_status": "热风温度",
        "CG_LT_GL_GL04_SBYCZB_status": "上部压差占比",
        "CG_LT_GL_GL04_XBYCZB_status": "下部压差占比",
      },
    },
    visible: false
  };

  defaultDisplay = [
    "CG_LT_GL_GL04_TQXZS_status",
    "CG_LT_GL_GL04_FYLL_status",
    "CG_LT_GL_GL04_RFWD_status",
    "CG_LT_GL_GL04_LFLL_status",
    "CG_LT_GL_GL04_FCokeRate_status",
    "CG_LT_GL_GL04_FCoalRate_status",
    "CG_LT_GL_GL04_XBYCZB_status",
    "CG_LT_GL_GL04_SBYCZB_status",];

  getTime = async () => {
    const resp = await getLatestTime({
      itemName: "HanFan",
    });
    const {start, end, current} = resp.detail
    let startTime = convertDateFromString(start)
    let endTime = convertDateFromString(end)
    let currentTime = convertDateFromString(current)

    const payload = {
      start: startTime,
      end: endTime,
      current: currentTime
    };
    return payload
  }

  async componentDidMount() {
    const {dispatch} = this.props;

    const payload = await this.getTime()

    this.scoreQuntileReq = requestAnimationFrame(() => dispatch({
      type: 'hanfan/getScoreQuntile', payload: {
        "start": dateFormat(payload.start),
        "end": dateFormat(payload.end)
      }
    }));
    this.predictionReqRef = requestAnimationFrame(() =>
      trigger(
        async () => {
          const payload = await this.getTime()
          const current = payload.current;
          this.props.dispatch({
            type: 'hanfan/predictionData',
            payload: {
              end: dateFormat(current)
            }
          });
        },
        new Date().valueOf(),
        60 * 1000,
        true,
        () => this.stopLoop));

    this.autoScoreReq = requestAnimationFrame(() =>
      trigger(
        async () => {
          const payload = await this.getTime()
          const current = payload.current;

          dispatch({
            type: 'hanfan/autoScore',
            payload: {
              end: dateFormat(current)
            }
          });

        },
        new Date().valueOf(),
        10 * 1000,
        true,
        () => this.stopLoop));

  }

  componentWillUnmount() {
    cancelAnimationFrame(this.predictionReqRef);
    cancelAnimationFrame(this.scoreQuntileReq);
    cancelAnimationFrame(this.autoScoreReq);
    this.stopLoop = true
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const {autoScore, scoreQuntile} = nextProps;
    // 及时更新display
    if (autoScore && autoScore !== prevState.autoScore) {
      return {
        autoScore
      }
    }

    if (scoreQuntile !== prevState.scoreQuntile && scoreQuntile) {
      return {
        scoreQuntile
      }
    }

    return null;
  }

  getStatus = status => {
    if (status === '数据异常') {
      return 'error'
    }
    if (status === '正常') {
      return 'processing'
    }

    if (status === '优秀') {
      return 'success'
    }

    if (status === '波动') {
      return 'warning'
    }
    if (status === '无') {
      return 'processing'
    }
  };

  showModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleOk = e => {
    this.setState({
      visible: false,
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  render() {

    const {
      width = 100,
      height = 300
    }
      = this.props;

    const {autoScore} = this.state;
    const {
      curScore = {
        CG_LT_GL_GL04_Score_predict: "",
        CG_LT_GL_GL04_Score: ""
      },
      shoude,
      bestValue,
      adjust = [],
      recommend = []
    } = autoScore

    // curScore = curScore ? curScore.toFixed(2):curScore;
    // bestScore = bestScore ? bestScore.toFixed(2):bestScore;
    // shoude = shoude ? shoude.toFixed(2):shoude;
    // const detail = Object.entries(autoScore.status).sort(
    //   (a, b) => a[1] > b[1]
    // ).slice(0, 5);

    // const detail = Object.entries(autoScore.status).slice(0, 8);

    const dom = adjust.map(item => (
      <Row key={item}>
        <Col span={6}>
          {item.desc}
        </Col>
        <Col span={6}>
          {item.status}
        </Col>
        <Col span={6}>
          {item.scope}
        </Col>
        <br/>
      </Row>));

    const recommendDom = recommend.map(item => (
      <Row key={item}>
        <Col span={12}>
          {item.key}
        </Col>
        <Col span={4}>
          {item.status}
        </Col>
        <Col span={8}>
          {item.recommend}
        </Col>
      </Row>
    ))

    return (
      <div style={{width: `${width}%`, height}}>
        <Descriptions title="" bordered>
          <Descriptions.Item label="预测值" span={2}>
            {curScore.CG_LT_GL_GL04_Score_predict}
          </Descriptions.Item>
          <Descriptions.Item label="当前值" span={2}>
            {curScore.CG_LT_GL_GL04_Score}
          </Descriptions.Item>
          <Descriptions.Item label="最佳值" span={2}>
            {bestValue}
          </Descriptions.Item>
          <Descriptions.Item label="收得率" span={2}>
            {shoude}
          </Descriptions.Item>
          <Descriptions.Item label="操作范围" span={3}>
            <div style={{height: "170px", overflowY: "auto"}}>
              {dom}
            </div>
          </Descriptions.Item>
          <Descriptions.Item label="操作调整" span={3}>
            <div style={{height: "100px", overflowY: "auto"}}>
              {recommendDom}
            </div>
          </Descriptions.Item>

        </Descriptions>

        <div>
          <Row>
            <a className={styles.showMore} style={{float: 'right'}} onClick={this.showModal}>显示详情</a>
          </Row>
        </div>

        <Modal
          width="80%"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <PredictionDetail/>
        </Modal>

      </div>

    )
  }
}

export default connect(({hanfan}) => ({
  autoScore: hanfan.autoScore
}))
(Prediction);
